<?php

use App\Models\Category;

/**
 * 所有分类
 */
if(!function_exists('categoryTree')){
    function categoryTree($status = false){
        $categories = Category::select(['id', 'pid', 'name', 'level', 'status'])
            ->when($status !== false, function($query) use($status){
                $query->where('status', $status);
            })
            ->where('pid', 0)
            ->with([
                'children'=>function($query)use($status){
                    $query->select(['id','pid','name','level','status'])
                          ->when($status !== false, function($query) use($status){
                            $query->where('status', $status);
                        });
                },
                'children.children' => function($query)use($status){
                    $query->select(['id','pid','name','level','status'])
                          ->when($status !== false, function($query) use($status){
                        $query->where('status', $status);
                    });
                }
            ])
            ->get();
        return $categories;
    }
}

/**
 * 缓存没被禁用的分类
 */
if(!function_exists('cache_category')){
    function cache_category(){
        return cache()->rememberForever('cache_category', function(){
            return categoryTree(1);
        });
    }
}

/**
 * 缓存所有的分类
 */
if(!function_exists('cache_category_all')){
    function cache_category_all(){
        return cache()->rememberForever('cache_category_all', function(){
            return categoryTree();
        });
    }
}

/**
 * 清空分类缓存
 */
if(!function_exists('cache_category_forget')){
    function cache_category_forget(){
        cache()->forget('cache_category');
        cache()->forget('cache_category_all');
    }
}
